package com.example.springstack.springboot.mongo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

/**
 * @author qiangfanghao
 * @date
 * MongodbTemplate多源配置(需要优化)
 */
@Slf4j
@Configuration
public class MongoTemplateConfig {


    @Autowired
    private ApplicationContext appContext;


    @Value("${spring.data.mongodb.uri}")
    private String mongoUri;

    @Value("${spring.data.mongodb.uri1}")
    private String mongoUri1;


    @Bean(name = "mongoTemplateMajor")
    @Primary
    public MongoTemplate mongoTemplateMajor() throws Exception {
        return new MongoTemplate(this.dbFactoryMajor(), this.mappingMongoConverter(this.dbFactoryMajor()));
    }


    @Bean
    @Primary
    public MongoDatabaseFactory dbFactoryMajor() {
        return new SimpleMongoClientDatabaseFactory(mongoUri);
    }

    @Bean(name = "mongoTemplateSecond")
    public MongoTemplate mongoTemplateSecond() throws Exception {
        return new MongoTemplate(this.dbFactorySecond(), this.mappingMongoConverter(this.dbFactorySecond()));
    }

    @Bean
    public MongoDatabaseFactory dbFactorySecond() {
        return new SimpleMongoClientDatabaseFactory(mongoUri1);
    }

    /**
     * 使用自定义的typeMapper去除写入mongodb时的“_class”字段
     * @throws Exception
     */
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory factory) throws Exception {

        MongoMappingContext mongoMappingContext =new MongoMappingContext();
        mongoMappingContext.setApplicationContext(appContext);

        MappingMongoConverter converter =new MappingMongoConverter(new DefaultDbRefResolver(factory), mongoMappingContext);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return converter;
    }

}
